import axios from 'axios'
import { getTokenFromCookie } from 'common/auth'
import { qsStringfy } from 'utils/qs'
import * as errorHandler from 'common/error-handler'

const headerToken = 'Authorization'

export const contentTypeWww = 'application/x-www-form-urlencoded';
export const contentTypeJson = 'application/json;charset=UTF-8';
export const defaultTimeout = 60 * 1000; // 改为一分钟！
export const longTimeout = 80 * 1000;

/* eslint-disable */
export function decorate() {
  const token = getTokenFromCookie()

  axios.defaults.withCredentials = false
  axios.defaults.header = true
  axios.defaults.timeout = longTimeout
  axios.defaults.headers['Content-Type'] = contentTypeJson
  
  // 如已登录，要带token
  if (token) {
    axios['defaults']['headers'][headerToken] = token
  }

  axios.interceptors.request.use(function (config) {
    if (config.method.toLowerCase() === 'post' && config.headers['Content-Type'] === contentTypeWww && config.data) {
      config.data = qsStringfy(config.data)
    }
    return config
  }, function (error) {
    // return Promise.reject(error)
    throw error
  })

  axios.interceptors.response.use(function (response) {
    let resData = response.data
    if (resData.code === '200' || resData.code === 200) {
      return resData
    } else {
      if (errorHandler.errorCodeMatch[resData.code]) {
        errorHandler.errorCodeMatch[resData.code](data)
      } else {
        // return Promise.reject(resData)
        throw resData
      }
    }
  }, function (error) {
    if (error.response) {
      const { status, data } = error.response
      if (status && errorHandler.errorCodeMatch[status]) {
        errorHandler.errorCodeMatch[status](data)
      } else {
        // return Promise.reject(error)
        throw error
      }
    } else {
      throw error
    }
  })
}

export function setHttpHeaderCookie(token) {
  axios.defaults.headers.token = token || getTokenFromCookie()
}
/* eslint-enable */

/* eslint-enable */
export function downloadData(excelUrl, reportName) {
  const token = getTokenFromCookie()
  fetch(excelUrl, {
    headers: {
      'Content-type': 'application/json;charset=UTF-8',
      [headerToken]: token
    }
  }).then(res => res.blob().then(blob => {
    const filename = `${reportName}.xls`
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename); // 兼容ie10
    } else {
      const a = document.createElement('a');
      document.body.appendChild(a) // 兼容火狐，将a标签添加到body当中
      const url = window.URL.createObjectURL(blob); // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
      a.href = url;
      a.download = filename;
      a.target = '_blank' // a标签增加target属性
      a.click();
      a.remove() // 移除a标签
      window.URL.revokeObjectURL(url);
    }
  }))
}
